package com.tanhua.commons.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    private static final long TOKEN_TIME_OUT = 1000 * 60 * 60 * 24;

    private static final String TOKEN_SECRET = "itcast";

    public static String getToken(Map param) {
        long currentTime = System.currentTimeMillis();
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS512, TOKEN_SECRET).setClaims(param).setExpiration(new Date(currentTime + TOKEN_TIME_OUT)).compact();
        return token;
    }

    public static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(TOKEN_SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 是否有效 true-有效，false-失效
     */
    public static boolean verifyToken(String token) {

        if (StringUtils.isEmpty(token)) {
            return false;
        }

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("itcast")
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return false;
        }

        return true;
    }
}
